<?php
/* ******************************
 * Pos aJax actions
* ******************************
*/

include('../../includes/classes/core.php');
include('../../includes/classes/pos_money_action.class.php');

$pos 	= new pos();
$action = $_REQUEST['act'];
$error	= '';
$data	= '';

switch ($action) {
	case 'get_list':
		$count		= $_REQUEST['count'];
		$hidden 	= $_REQUEST['hidden'];
		$object_id	= $_REQUEST['obj_id'];	
		
		$rResult = mysql_query("
 									SELECT 		`sale_transaction_detail`.`id`,
												`production`.`name`,
												`sale_transaction_detail`.`cost`,
												`sale_transaction_detail`.`product_quantity`,
												 ROUND(`sale_transaction_detail`.`cost` * `sale_transaction_detail`.`product_quantity`, 2 )
									FROM 		`sale_transaction` 
									LEFT JOIN 	`sale_transaction_detail`
									ON 			`sale_transaction`.`id` = `sale_transaction_detail`.`transaction_id`
									LEFT JOIN 	`production`
									ON 			`sale_transaction_detail`.`production_id` = `production`.`id`
									WHERE   	`sale_transaction`.`object_id` = $object_id && `status` = 1
    	    						");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
			$error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
					if($i == ($count - 1)){
						$row[] = '<a class="pos-prod-delete"/>' . $aRow[$hidden] . '</a>';
					}
				}
				$data['aaData'][] = $row;
			}
		}
		
		break;
		
	case 'add_prod':
		
		$user_id		= $_COOKIE['USERID'];
		$object_id 		= $_REQUEST['obj_id'];
		$prod_id 		= $_REQUEST['id'];
		$prod_quantity	= $_REQUEST['quantity'];
		
		$price_type		= $_REQUEST['price'];
		$price			= GetProductPrice($prod_id);
		
		$list			= json_decode(stripslashes($_REQUEST['list']));		
		$check 			= CheckList($list);
		$s_price	    = getProdSelfCost($prod_id);
		
		$status	= CheckObjectStatus($object_id);
		if (!$status) { // თუ ობიექტზე ტრანზაქცია გახსნილი არ არის
			$trans_id = AddTransaction($user_id, $object_id);
			if(IsEmptyList($prod_id)){ // თუ ცარიელი მასივია (რეცეპტის)
				if(!$price){ //ფასი არ არის დაფიქსირებული
					$error = 'დააფიქსირეთ პროდუქტის ფასი!';
				}else{
					$rec_self_price = GetRecipieSelfCostEmptyList($prod_id);
					$rec_price  = GetRecipieCostEmptyList($prod_id);
					$t_id = AddProdRecipie($user_id, GetTransactionId($object_id), $prod_id, $prod_quantity, $rec_self_price, $rec_price);
					//$tr_id	= mysql_insert_id();
					AddHiddenRecProducing($user_id, $t_id, $prod_id);
				}
			}else
			if(!$check){ //რეცეპტის შემთხვევა			
				$ingredient_exists = CheckIngredientsExists($list, $object_id, $prod_quantity);  // ინგრედიენტების საკმარისი რაოდენობის შემოწმება		
				if ($ingredient_exists) { //ინგრედიენტების საკმარისი რაოდენობა
					if(!$price){
						$error = 'დააფიქსირეთ პროდუქტის ფასი!';
					}else{
						$rec_self_price = GetRecipieSelfCost2($prod_id, $list);
						$rec_price  = GetRecipieCost($prod_id, $list);
						$t_id = AddProdRecipie($user_id, GetTransactionId($object_id), $prod_id, $prod_quantity, $rec_self_price, $rec_price);
						//$tr_id	= mysql_insert_id();
						AddHiddenRecProducing($user_id, $t_id, $prod_id);
						for ($i = 0; $i < count($list); $i++) {
								AddRecProducing($user_id, $t_id, $prod_id, $list[$i][0], $list[$i][1]*$prod_quantity);	
				 		}						
					} 
				} else{
					DeleteTransaction($object_id);
					$error = GetIngredientInfo($object_id, $list);
					}
			}else { //Tu produqtia
				
			$prod_exist = CheckProductionExists($prod_id, $prod_quantity, $object_id);
			if ($prod_exist) {					
				if(!$price){
					$error = 'დააფიქსირეთ პროდუქტის ფასი!';
				}else{									 
							AddProd($user_id, $object_id, $trans_id, $prod_id, $prod_quantity, $s_price, $price);						
					}
				}else{
					DeleteTransaction($object_id);
					$error = GetProductionInfo($object_id, $prod_id);
				}
			}
		 } else {
		 	if(IsEmptyList($prod_id)){ // tu carieli masivia
		 		if(!$price){
		 			$error = 'დააფიქსირეთ პროდუქტის ფასი!';
		 		}else{
			 		$rec_self_price = GetRecipieSelfCostEmptyList($prod_id);
			 		$rec_price  = GetRecipieCostEmptyList($prod_id);
			 		$t_id = AddProdRecipie($user_id, GetTransactionId($object_id), $prod_id, $prod_quantity, $rec_self_price, $rec_price);
			 		//$tr_id	= mysql_insert_id();
			 		AddHiddenRecProducing($user_id, $t_id, $prod_id);
		 		}
		 	}else
			if(!$check){ //tu receptia
			
			$ingredient_exists = CheckIngredientsExists($list, $object_id, $prod_quantity);
				if ($ingredient_exists) {
					if(!$price){
						$error = 'დააფიქსირეთ პროდუქტის ფასი!';
					}else{
						$rec_self_price = GetRecipieSelfCost2($prod_id, $list);
						$rec_price  = GetRecipieCost($prod_id, $list);
						$t_id = AddProdRecipie($user_id, GetTransactionId($object_id), $prod_id, $prod_quantity, $rec_self_price, $rec_price);
						//$tr_id	= mysql_insert_id();
						AddHiddenRecProducing($user_id, $t_id, $prod_id);
						for ($i = 0; $i < count($list); $i++) {
							AddRecProducing($user_id, $t_id, $prod_id, $list[$i][0], $list[$i][1]*$prod_quantity);
				 		}
					} 
				} else{
					$error = GetIngredientInfo($object_id, $list);
					}
			}else { //Tu produqtia
				
			$quantity = GetProdQuantity($status, $prod_id);
			$prod_exist = CheckProductionExists($prod_id, $prod_quantity, $object_id);
			if ($prod_exist) {					
				if(!$price){
					$error = 'დააფიქსირეთ პროდუქტის ფასი!';
				}else{							 
							AddProd($user_id, $object_id, GetTransactionId($object_id), $prod_id, $prod_quantity, $s_price, $price);						
					}
				}else{
					$error = GetProductionInfo($object_id, $prod_id);
				}
			}
		}

		break;
		
	case 'add_prod_seo':
			$prod			= $_REQUEST['name'];
			$object_id 		= $_REQUEST['obj_id'];
			$prod_id 		= GetProductID($prod);
			$trans_id		= $_REQUEST['trans_id'];
			$user_id		= $_COOKIE['USERID'];
				
			$price			= GetProductPrice($prod_id);
			$s_price	    = getProdSelfCost($prod_id);
		
			$isProduct = IsProduct($prod_id);
				
			if($isProduct){
				$status	= CheckObjectStatus($object_id);
				if (!$status) {
						
					$trans_id = AddTransaction($user_id, $object_id);
					$prod_exist = CheckProductionExists($prod_id, 1, $object_id);
					if ($prod_exist) {
						AddProd($user_id, $object_id, GetTransactionId($object_id), $prod_id, 1, $s_price, $price);
					}else{
						$error = 'არასაკმარისი პროდუქტი!';
					}
				}else{
					$prod_exist = CheckProductionExists($prod_id, 1, $object_id);
					if ($prod_exist) {
							
						AddProd($user_id, $object_id, GetTransactionId($object_id), $prod_id, 1, $s_price, $price);
					}else{
						$error = 'არასაკმარისი პროდუქტი!';
					}
				}
			}else{
				$error = 'პროდუქტი ასეთი შტრიხკოდით ან დასახელებით  ვერ მოიძებნა!
* შეამოწმეთ "ფასების სიაში" ან "პროდუქტებში"';
			}
				
			break;
		
    case 'delete_prod':
		$trans_det_id 	= $_REQUEST['trans_id'];
		$object_id 		= $_REQUEST['obj_id'];
		
		DeleteLog($trans_det_id);
		
		DeleteProduct($trans_det_id);
		if(CheckTransStatus($object_id)){
			DeleteTransaction($object_id);
		}
		
        break;
	case 'save_transaction':
		$object_id 		= $_REQUEST['obj_id'];
		
		$status	= CheckObjectStatus($object_id);
				
		if (!$status) {
			$error = 'პროდუქციის სია ცარიელია!';
		}else {
			SaveTransaction($object_id);
		}
		
		break;
	case 'abort_transaction':
		$object_id 		= $_REQUEST['obj_id'];
        
		AbortTransaction($object_id);
		
		break;        	        	
	case 'get_prod_count':
		$object_id 		= $_REQUEST['obj_id'];
		
		$data	= array('prod_count' => GetProdCount($object_id));
		
        break;
	case 'get_sum_price':
		$object_id 		= $_REQUEST['obj_id'];
		
		$data	= array('sum_price' => GetSumPrice($object_id));
		
        break;
    case 'select_pos':
		$data	= array('page' => SelectPOS());
		
        break;
	case 'suspended_page':
		$object_id 		= $_REQUEST['obj_id'];
		$data	= array('page' => GetSuspendedPage($object_id));
		
		break;
		
	case 'restore_suspended':
		$object_id 		= $_REQUEST['obj_id'];
		$trans_id		= $_REQUEST['trans_id'];
		
		$status	= CheckObjectStatus($object_id);
		
		if (!$status) {
			RestoreSuspended($trans_id);
		}else {
			SaveTransaction($object_id);
			RestoreSuspended($trans_id);
		}		
		
		break;
	case 'cancel_suspend':
		$trans_id		= $_REQUEST['trans_id'];
		
		CancelSuspended($trans_id);
		
		break;
    case 'payment_done':
		$object_id			= $_REQUEST['obj_id'];
		$user_id            = $_COOKIE['USERID'];
		$pay_type           = $_REQUEST['pay_type'];
		$payed_money        = $_REQUEST['payed_money'];		
		$sum_cost			= GetSumPrice($object_id);
		$sum_self_cost		= GetSumSelfPrice($object_id);
	//	$trans_id			= $_REQUEST['trans_id'];
		
		if($sum_cost <= $payed_money){
			$calculate			= Calculate($object_id);
	        PayDone($user_id, $object_id, $sum_cost, $sum_self_cost, $payed_money, $pay_type);
		}else{
			$error = "დაფიქსირდა შეცდომა პროდუქტების შეყვანისას!          **სცადეთ თავიდან.";
		}
		
        break;
        
     case 'get_main_menu':
     	//$object_id 		= $_REQUEST['obj_id'];
     	$data	= array('page' => getMainMenu());
     	
     	break;
     	
     case 'get_sub_menu':
     	$category_id 	= $_REQUEST['id'];
     	$data			= array('page' => getSubMenu($category_id));
     	
     	break;

     case 'prod_ing_page':
     	$object_id 	= $_REQUEST['obj_id'];
     	$prod_id 	= $_REQUEST['prod_id'];
     	$check		= CheckProdType($prod_id);

     	if(!$check){
     		$data		= array('page' => GetProdPage($object_id, $prod_id));
     	}else {
     		$data		= array('page' => GetProdIngPage($object_id, $prod_id)); }
     	
     	break;
     	
     case 'print_check' :
     	$price     = $_REQUEST['price'];
     	printCheck($price);
     	break;
     	
     case 'add-money-page':
     	$object_id = $_REQUEST['obj_id'];
     	
     	$data		= array('page' => GetAddSalary($object_id));
     	break;     
     	
     case 'take-money-page':
     	$object_id = $_REQUEST['obj_id'];
     
     	$data		= array('page' => GetTakeSalary($object_id));
     
     	break;	
     	
     case 'add-money':
     	$object_id 	  = $_REQUEST['obj_id'];
     	$money		  = $_REQUEST['money-amount'];
     	$comment      = $_REQUEST['comment'];
     	$username     = $_REQUEST['username'];
     	$password     = $_REQUEST['password'];
     	
     	if (is_numeric($money)){
     		GLOBAL	$pos;
     		$check = $pos->CheckUser($username, $password);
     		if($check){
     			$pos->pos_in(GetUserId($username), $object_id, $money, $comment);
     		}else{
     			$error = "მომხმარებლის სახელი ან პაროლი არასწორია!";
     	}
     	}else{
     		$error = "შეიყვანეთ თანხის რაოდენობა \n *მხოლოდ ციფრები!";
     	}
     	
     	break;
     	
     case 'take-money':
     	$object_id 	  = $_REQUEST['obj_id'];
     	$money		  = $_REQUEST['money-amount'];
     	$comment      = $_REQUEST['comment'];
     	$username     = $_REQUEST['username'];
     	$password     = $_REQUEST['password'];
     	$array        = GetWarehouseMoney();
     	
     	if (is_numeric($money)){
     		GLOBAL	$pos;
     		$check = $pos->CheckUser($username, $password);
     		if($check){
     			if($array >= $money){
     				$pos->pos_out(GetUserId($username), $object_id, $money, $comment);
     			}else{
     				$error = "არასაკმარისი თანხა!";
     			}
     		}else{
     			$error = "მომხმარებლის სახელი ან პაროლი არასწორია!";
     		}
     	}else{
     		$error = "შეიყვანეთ თანხის რაოდენობა \n *მხოლოდ ციფრები!";
     	}
     	
     	break;     	
     case 'pos-check':
     	$object_id 	  = $_REQUEST['obj_id'];
     	$real_money	  = $_REQUEST['money-amount'];
     	$user_id      = $_COOKIE['USERID'];
     	$comment      = $_REQUEST['comment'];
     	

     	InsertPosCheck($user_id, $object_id, $comment, $real_money);
     	
     	break;
    	
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Pos Functions
* ******************************
*/

function DeleteLog($trans_det_id){

	$date 			= date('Y-m-d H:i:s');
	$user_id        = $_COOKIE['USERID'];
	$res = mysql_fetch_assoc(mysql_query("SELECT 	sale_transaction_detail.transaction_id,
													sale_transaction_detail.id,
													sale_transaction_detail.production_id,
													sale_transaction_detail.product_quantity,
													sale_transaction_detail.self_cost,
													sale_transaction_detail.cost
											FROM 	sale_transaction_detail
											WHERE 	sale_transaction_detail.id = $trans_det_id"));
												
	mysql_query("INSERT INTO sale_transaction_log
					(user_id, sale_transaction_id, sale_transaction_detail_id, date, production_id, quantity, self_cost, cost, action)
				VALUES
					($user_id, $res[transaction_id], $res[id], '$date', $res[production_id], $res[product_quantity], $res[self_cost], $res[cost], 2)");

}

function InsertLog($user_id, $trans_id, $trans_det_id, $prod_id, $prod_quantity, $s_price, $price){

	$date 			= date('Y-m-d H:i:s');
	$user_id        = $_COOKIE['USERID'];

	mysql_query("INSERT INTO sale_transaction_log
	(user_id, sale_transaction_id, sale_transaction_detail_id, date, production_id, quantity, self_cost, cost, action)
	VALUES
	($user_id, $trans_id, $trans_det_id, '$date', $prod_id, $prod_quantity, $s_price, $price, 1)");

}

function IsProduct($prod_id){
	$check = false;
	$result =mysql_query("SELECT      `production`.`code`
			FROM      `pricelist`
			LEFT JOIN `production` ON `pricelist`.`production_id` = `production`.`id`
			WHERE 	  `pricelist`.`production_id` = $prod_id
			");
	$row_number = mysql_num_rows($result);

	if($row_number == 1){
	$check = true;
	}

	return $check;
}

function InsertPosCheck($user_id, $object_id, $comment, $real_money){
	$date = date('Y-m-d H:i:s');
	$res = mysql_fetch_assoc(mysql_query("SELECT
			sale_transaction.user_id AS `last_user`
			FROM sale_transaction
			WHERE sale_transaction.object_id = $object_id
			ORDER BY sale_transaction.end_date DESC
			LIMIT 1"));
			$last_user = $res['last_user'];

			$arr = GetWarehouseMoney();


			mysql_query("INSERT INTO pos_check
			(pos_check.pos_id, pos_check.pos_user_id, pos_check.last_pos_user_id, pos_check.check_date, pos_check.money_in_pos, pos_check.real_money, pos_check.comment, pos_check.`status`)
			VALUES
			($object_id, $user_id, $last_user, '$date', $arr, $real_money, '$comment', 0)");

}

function GetUserId($username){
	$res = mysql_fetch_assoc(mysql_query("SELECT `users`.`id` AS `id`
			FROM `users`
			WHERE `users`.`username` = '$username'"));

	return $res['id'];
}

function IsEmptyList($prod_id){

	$result = mysql_fetch_assoc(mysql_query("SELECT   IF(SUM(recipie.visible) = 0, 0, 1) AS `check`
												FROM  recipie
												WHERE recipie.recipie_id = $prod_id"));

	if($result['check'] == 0){
		return true;
	}else{
		return false;
	}
}


function GetWarehouseMoney(){
	$result  = array();
	
	$res0 = mysql_query("SELECT     IF(pos_check.real_money IS NULL, 0, pos_check.real_money) AS `money`,
			       									  pos_check.check_date AS `date`
											FROM      `pos_check`
											LEFT JOIN  object ON object.id = pos_check.pos_id
											WHERE     object.type = 9 AND pos_check.`status` = 1
											ORDER BY   pos_check.check_date DESC
											LIMIT      1");
	$res01 = mysql_fetch_assoc($res0);
	
	$date = $res01['date'];

	
	if(mysql_num_rows($res0) == 0){
		
		$date = '0000-00-00 00:00:00';
	}
	
	$res1 = mysql_fetch_assoc(mysql_query("SELECT        ROUND(SUM(pos_money_action.money), 2) AS `in_money`
						FROM         pos_money_action
						LEFT JOIN  object ON object.id = pos_money_action.pos_id
						WHERE       object.type = 5 AND pos_money_action.action =1 AND pos_money_action.date >= '$date'"));
						
	$res3 = mysql_fetch_assoc(mysql_query("
						
						SELECT        ROUND(SUM(sale_transaction.sum_cost), 2) AS `in_money`
						FROM          sale_transaction
						LEFT JOIN  object ON object.id = sale_transaction.object_id
						WHERE       sale_transaction.pay_type = 1 AND object.type = 5 AND sale_transaction.end_date >= '$date'"));
						
	$res4 = mysql_fetch_assoc(mysql_query("
						SELECT        ROUND(SUM(pos_money_action.money), 2) AS `in_money`
						FROM         pos_money_action
						LEFT JOIN  object ON object.id = pos_money_action.pos_id
						WHERE       object.type = 9 AND pos_money_action.action =1 AND pos_money_action.date >= '$date'"));
						
	$res5 = mysql_fetch_assoc(mysql_query("
						SELECT        ROUND(SUM(sale_transaction.sum_cost), 2) AS `in_money`
						FROM          sale_transaction
						LEFT JOIN  object ON object.id = sale_transaction.object_id
						WHERE       sale_transaction.pay_type = 1 AND object.type = 9 AND sale_transaction.end_date >= '$date'
						"));

	$res2 = mysql_query("SELECT      SUM(pos_money_action.money) AS `out_money`
											FROM       pos_money_action
											LEFT JOIN object ON object.id = pos_money_action.pos_id
											WHERE     object.type = 5 AND pos_money_action.action = 2 AND pos_money_action.date >= '$date'
											
											UNION ALL 
											
											SELECT      SUM(pos_money_action.money) AS `out_money`
											FROM       pos_money_action
											LEFT JOIN object ON object.id = pos_money_action.pos_id
											WHERE     object.type = 9 AND pos_money_action.action = 2  AND pos_money_action.date >= '$date'
						 ");
	
// 	$res1Arr = array();
	$res2Arr = array();
	
// 	while($row1 = mysql_fetch_assoc($res1)){
// 		$res1Arr[] = $row1['in_money'];
// 	}

	while($row2 = mysql_fetch_assoc($res2)){
		$res2Arr[] = $row2['out_money'];
	}
	
	$r1 = $res1['in_money'] + $res3['in_money'];
	$r2 = $res4['in_money'] + $res5['in_money'];
	//$result[0] = $r1 - $res2Arr[0];
	$result = $r2 - $res2Arr[1] + $res01['money'];
	return $result;
}

function GetRecipieCostEmptyList($prod_id){
	$res  = mysql_fetch_assoc(mysql_query("SELECT       ROUND(`pricelist`.`price_wholesale`,2) AS `price`
			FROM        production
			LEFT JOIN   pricelist ON production.id = pricelist.production_id
			LEFT JOIN   recipie ON recipie.recipie_id = production.id
			LEFT JOIN   reserve ON recipie.ingredient_id = reserve.production_id
			WHERE       production.id IN (SELECT pricelist.production_id FROM pricelist) && production.id=$prod_id
			GROUP BY    production.id
			HAVING      SUM(reserve.quantity - reserve.sold)>0"));
	return $res['price'];
}


function GetRecipieCost($prod_id, $list){
	$res  = mysql_fetch_assoc(mysql_query("SELECT       ROUND(`pricelist`.`price_wholesale`,2) AS `price`			
											FROM        production
											LEFT JOIN   pricelist ON production.id = pricelist.production_id
											LEFT JOIN   recipie ON recipie.recipie_id = production.id
											LEFT JOIN   reserve ON recipie.ingredient_id = reserve.production_id
											WHERE       production.id IN (SELECT pricelist.production_id FROM pricelist) && production.id=$prod_id
											GROUP BY    production.id
											HAVING      SUM(reserve.quantity - reserve.sold)>0"));
	$sum = 0;
	
	for($i = 0; $i<count($list); $i++){
		
		$id       = $list[$i][0];
		$quantity = $list[$i][1];
		$amount   = $list[$i][2];
		
		$res2 = mysql_fetch_assoc(mysql_query("SELECT      recipie.ingredient_id,
						        						   IF(recipie.quantity < $quantity, ROUND(($quantity / recipie.quantity -1) *  recipie.price, 3), 0) AS `price1`
												FROM       recipie
												LEFT JOIN  pricelist ON pricelist.production_id = recipie.recipie_id
												WHERE      recipie.recipie_id = $prod_id AND recipie.ingredient_id = $id AND recipie.default_amount != 0"));
		$sum+=$res2['price1'];
		
		$res3 = mysql_fetch_assoc(mysql_query("SELECT IF($amount >= 1, recipie.price * $amount, 0) AS `add_price`
												FROM `recipie`
												where recipie.recipie_id = $prod_id AND recipie.default_amount = 0 AND recipie.ingredient_id = $id"));
		
		$sum+=$res3['add_price'];
	}
	
	
	
	return round($res['price']+$sum, 2);
}

function GetRecipieSelfCostEmptyList($prod_id)
{
	$res = mysql_fetch_assoc(mysql_query("
			SELECT       ROUND(SUM((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = rec.ingredient_id ) * rec.quantity * rec.default_amount),2)  AS `self_price`
			FROM         `recipie` AS rec
			WHERE        `rec`.`recipie_id` = $prod_id AND `rec`.`visible` = 0
			GROUP BY     rec.recipie_id
			"));

	return $res['self_price'];
}

function GetRecipieSelfCost2($prod_id, $list)
{
	$sum = 0;
	$res = mysql_fetch_assoc(mysql_query("
									SELECT       ROUND(SUM((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = rec.ingredient_id ) * rec.quantity * rec.default_amount),2)  AS `self_price`       
									FROM         `recipie` AS rec 
									WHERE        `rec`.`recipie_id` = $prod_id AND `rec`.`visible` = 0
									GROUP BY     rec.recipie_id
			"));
	
	$sum += $res['self_price'];
	
	for($i = 0; $i<count($list); $i++){
	
		$id       = $list[$i][0];
		$quantity = $list[$i][1];
		//$amount   = $list[$i][2];
	
		$res2 = mysql_fetch_assoc(mysql_query("SELECT    	DISTINCT `recipie`.`id`,
															ROUND(reserve.price * $quantity, 2) AS `s_price`
												FROM		`recipie`
												LEFT JOIN 	`production` ON `recipie`.`ingredient_id` = `production`.`id`
												LEFT JOIN 	reserve ON recipie.ingredient_id = reserve.production_id
												WHERE 		`recipie`.`recipie_id` = $prod_id AND recipie.ingredient_id = $id AND `recipie`.`visible` = 1 
				"));
		$sum+=$res2['s_price'];
	}
	
	return $sum;
}

function GetProductionInfo($object_id, $prod_id){
	$warehouse = GetWarehouseObject($object_id);
	$info ="მარაგში არ არის პროდუქციის საკმარისი რაოდენობა\n\n";
	$res = mysql_fetch_assoc(mysql_query("SELECT      `production`.`name` AS `name`, SUM(`reserve`.`quantity` - `reserve`.`sold`) - ".GetProductionQuantity($prod_id)." AS `quantity`
											FROM 	  `reserve`
									   LEFT JOIN      `production` ON `reserve`.`production_id`=`production`.`id`
											WHERE     `reserve`.`object_id`=$warehouse && `reserve`.`production_id`= $prod_id"));
	$info .= $res['name'] . " მარაგში არის  " . $res['quantity'] . " !\n";

	return $info;
}

function CheckProductionExists($prod_id, $prod_quantity, $object_id){

	$check = true;
	$warehouse = GetWarehouseObject($object_id);

	$res = mysql_fetch_assoc(mysql_query("SELECT 	IF(SUM(reserve.quantity - reserve.sold) - ".GetProductionQuantity($prod_id)." >= $prod_quantity, 1, 0) AS `check`
											FROM 	`reserve`
											WHERE 	reserve.object_id = $warehouse && reserve.production_id = $prod_id
											GROUP 	BY reserve.object_id, reserve.production_id"));
	if($res['check']==0){
		$check = true;
	}


	return $check;
}

function GetProductionQuantity($prod_id){
$res = mysql_fetch_assoc(mysql_query("SELECT	IF(SUM(`sale_transaction_detail`.`product_quantity`) > 0, SUM(`sale_transaction_detail`.`product_quantity`), 0) AS `sum`
										FROM	`sale_transaction_detail`
								   LEFT JOIN    `sale_transaction` ON `sale_transaction_detail`.`transaction_id`=`sale_transaction`.`id`
									   WHERE	`sale_transaction`.`status`=1 && `sale_transaction_detail`.`production_id` = $prod_id"));
		return $res['sum'];
}

function GetIngredientInfo($object_id, $list){
	
	$warehouse = GetWarehouseObject($object_id);
	$info ="მარაგში არ არის ინგრედიენტების საკმარისი რაოდენობა\n\n";
	for($i=0; $i<count($list); $i++){
		$res = mysql_fetch_assoc(mysql_query("SELECT  `production`.`name` AS `name`, SUM(`reserve`.`quantity` - `reserve`.`sold`) - ".GetIngredientQuantity($list[$i][0])." AS `quantity`
											FROM 	  `reserve`
											LEFT JOIN `production` ON `reserve`.`production_id`=`production`.`id`
											WHERE     `reserve`.`object_id`=$warehouse && `reserve`.`production_id`= ".$list[$i][0].""));
		$info .= $res['name'] . " მარაგში არის  " . round($res['quantity'], 3) . " !\n";
	}
	return $info;
}

function GetIngredientQuantity($prod_id){
	$res = mysql_fetch_assoc(mysql_query("SELECT IF(SUM(`recipie_producing`.`quantity`) > 0, SUM(`recipie_producing`.`quantity`), 0)  AS `sum`
											FROM `recipie_producing`
											LEFT JOIN `sale_transaction_detail` ON `recipie_producing`.`transaction_detail_id`=`sale_transaction_detail`.`id`
											LEFT JOIN `sale_transaction` ON `sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
											WHERE `recipie_producing`.`production_id` = $prod_id && `sale_transaction`.`status`=1"));
	if($res['sum'] != 0){
		return $res['sum'];
	}else{
		return 0;		
	}
}

function CheckIngredientsExists($list, $object_id, $prod_quantity){
	
	$check = true;
	$warehouse = GetWarehouseObject($object_id);

	for($i=0; $i<count($list); $i++){	

	$res = mysql_fetch_assoc(mysql_query("SELECT IF(SUM(reserve.quantity - reserve.sold) - ".GetIngredientQuantity($list[$i][0])." >= ".$list[$i][1]*$prod_quantity.", 1, 0) AS `check`
											FROM `reserve`
											WHERE reserve.object_id = $warehouse && reserve.production_id = ".$list[$i][0]."
											GROUP BY reserve.object_id, reserve.production_id"));
		if($res['check']==0){
			$check = true;  break;
		}
	}
	
	return $check;
}

function getRecipieSelfCost($trans_id){
	$res= mysql_fetch_assoc(mysql_query("
						SELECT    recipie_producing.recipie_id,
						SUM(ROUND(recipie_producing.quantity * reserve.price, 2)) AS `self_cost`
						FROM      recipie_producing
						LEFT JOIN    reserve ON reserve.production_id = recipie_producing.production_id
						WHERE        recipie_producing.transaction_detail_id = $trans_id
						GROUP BY  recipie_producing.recipie_id "));
	
	return $res['self_cost'];
	
}

function getProdSelfCost($prod_id){
	$res = mysql_fetch_assoc(mysql_query("	SELECT    	  `reserve`.`price` AS `price`
												FROM      `reserve`
												WHERE      `reserve`.`production_id` = $prod_id
												GROUP BY  `reserve`.`production_id`
												"));
	
	return $res[price];
}


function CheckList($list){
	
	$check = false;
	if(empty($list)){
		$check = true;
	}
	
	return $check;
}

function CheckProdType($prod_id){
	
	$check	=	false;
	$res	=	mysql_query("SELECT      recipie.recipie_id
								FROM     recipie
								WHERE    recipie.recipie_id = $prod_id");
			
	$numRows = mysql_num_rows($res);
	if($numRows > 0){
		$check	=	true;
	}
	
	return $check;
}


//Function for add recipie
function AddProdRecipie($user_id, $trans_id, $prod_id, $prod_quantity, $s_price, $price){

		mysql_query("	INSERT INTO `sale_transaction_detail`
		(`user_id`, `transaction_id`, `production_id`, `product_quantity`, `self_cost`, `cost`)
		VALUES
		($user_id, $trans_id, $prod_id, $prod_quantity, $s_price, $price)");
		
		$trans_det_id = mysql_insert_id();
		InsertLog($user_id, $trans_id, $trans_det_id, $prod_id, $prod_quantity, $s_price, $price);
		
		return $trans_det_id;
}

function AddProd($user_id, $object_id, $trans_id, $prod_id, $prod_quantity, $s_price, $price){

	$result = mysql_query("	SELECT	`sale_transaction_detail`.`production_id`
							FROM	`sale_transaction_detail` LEFT JOIN `production`
								ON	`sale_transaction_detail`.`production_id` = `production`.`id` LEFT JOIN `sale_transaction`
								ON	`sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
							WHERE (`sale_transaction`.`object_id` = '$object_id' && `status` = 1) && (`sale_transaction_detail`.`production_id` = '$prod_id')");
	
	if (mysql_num_rows($result)){
		mysql_query("	UPDATE
						`sale_transaction_detail` LEFT JOIN `sale_transaction`
							ON sale_transaction_detail.transaction_id = sale_transaction.id
							SET
							`sale_transaction_detail`.`product_quantity` =  `sale_transaction_detail`.`product_quantity` + $prod_quantity
							WHERE
						`sale_transaction_detail`.`production_id` = $prod_id &&  `sale_transaction`.`status` = 1 && transaction_id = $trans_id");
	
	}else{
		mysql_query("	INSERT INTO `sale_transaction_detail`
					     (`user_id`, `transaction_id`, `production_id`, `product_quantity`, `self_cost`, `cost`)
					VALUES
					     ($user_id, $trans_id, $prod_id, $prod_quantity, $s_price, $price)");
	}
	
	$trans_det_id = mysql_insert_id();
	InsertLog($user_id, $trans_id, $trans_det_id, $prod_id, $prod_quantity, $s_price, $price);
}

function AddRecProducing($user_id, $trans_det_id, $rec_id, $prod_id, $quantity){
	mysql_query("INSERT INTO `recipie_producing`
	(`user_id`, `transaction_detail_id`, `recipie_id`, `production_id`, `quantity`)
	VALUES
	($user_id, $trans_det_id, $rec_id, $prod_id, $quantity)");
}

function AddHiddenRecProducing($user_id, $trans_det_id, $rec_id){
	$result = mysql_query("SELECT  rec.recipie_id AS `id`,
							       `rec`.ingredient_id AS `ingredient_id`,
							       `rec`.`quantity`*`rec`.`default_amount` AS `quantity`  
							FROM 	 `recipie` AS rec 
							WHERE  `rec`.`recipie_id` = $rec_id AND `rec`.`visible` = 0
							     	");
	while($row = mysql_fetch_assoc($result)){
		mysql_query("INSERT INTO `recipie_producing`
			(`user_id`, `transaction_detail_id`, `recipie_id`, `production_id`, `quantity`)
			VALUES
			($user_id, $trans_det_id, {$row['id']}, {$row['ingredient_id']}, {$row['quantity']})");
	}
}

function DeleteProduct($trans_det_id)
{
    mysql_query("DELETE 
				 FROM
	    			`sale_transaction_detail`
				 WHERE
					`id` = $trans_det_id");
    mysql_query("DELETE
				FROM
				`recipie_producing`
				 WHERE
				`transaction_detail_id`	= $trans_det_id");
}

function DeleteTransaction($object_id)
{
    mysql_query("UPDATE `sale_transaction`
    			 SET	status = 6
				 WHERE
					`object_id` = $object_id && `status` = 1");
}

function AddTransaction($user_id, $object_id)
{
	$start_date = date('Y-m-d H:i:s');
	mysql_query("INSERT INTO `sale_transaction`
					(`user_id`, `object_id`, `start_date`) 
				 VALUES
					($user_id, $object_id, '$start_date')");
	return GetTransactionId($object_id);	
}

function SaveTransaction($object_id)
{
	mysql_query("
				UPDATE        `sale_transaction_detail`
				LEFT JOIN     `sale_transaction`
					ON 		  `sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
				SET           `sale_transaction`.`status` = 2
				WHERE         `sale_transaction`.`object_id` = $object_id   AND  `sale_transaction`.`status` = 1
				");
}

function AbortTransaction($object_id)
{
	mysql_query("
				UPDATE		`sale_transaction_detail`
				LEFT JOIN	`sale_transaction`
					ON		`sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
				SET			`sale_transaction`.`status` = 3
				WHERE		`sale_transaction`.`object_id` = $object_id   AND  `sale_transaction`.`status` = 1
	            ");
}

function RestoreSuspended($trans_id)
{
	mysql_query("
					UPDATE		`sale_transaction`
						SET		`sale_transaction`.`status` = 1
					WHERE		`sale_transaction`.`id` = $trans_id
				");
}

function CancelSuspended($trans_id)
{
	mysql_query("
					UPDATE		`sale_transaction`
						SET		`sale_transaction`.`status` = 3
					WHERE		`sale_transaction`.`id` = $trans_id
				");
}

function GetProductID($prod)
{
	$prod = htmlspecialchars($prod, ENT_QUOTES);
	$res = mysql_fetch_assoc(mysql_query("	SELECT `id`
											FROM `production`
											WHERE `code` = '$prod' || `name` = '$prod'"));
	return $res['id'];
}

function CheckObjectStatus($object_id)
{
    $res = mysql_query("SELECT `sale_transaction`.`id`
					    FROM `object` LEFT JOIN `sale_transaction`
							ON `object`.`id` = `sale_transaction`.`object_id`
					    WHERE `object`.`id` = $object_id && `sale_transaction`.`status` = 1");
	if ( mysql_num_rows($res) == 0){
		return false;
	}
	$row = mysql_fetch_assoc($res);
	return $row['id'];
}

function CheckTransStatus($object_id)
{
    $res = mysql_query("SELECT *
						FROM `sale_transaction` RIGHT JOIN `sale_transaction_detail`
							ON `sale_transaction`.`id` = `sale_transaction_detail`.`transaction_id`
						WHERE `object_id` = $object_id && `status` = 1");
	if (mysql_num_rows($res) == 0){
		return true;
	}
	return false;
}

function GetProductPrice($prod_id) 
{

    $res = mysql_query("SELECT 		`pricelist`.`price_wholesale` AS `price` 
					    FROM 		`pricelist` 
    					INNER JOIN 	`production` 
				   		ON 			`pricelist`.`production_id` = `production`.`id`
   					    WHERE 		`production`.`id` = $prod_id");
    if (mysql_num_rows($res) == 0 ){
		return false;
	}		
	$row = mysql_fetch_assoc($res);
	
	return $row[price];
}

function GetProdCount($object_id)
{
    $res = mysql_query("SELECT SUM(`sale_transaction_detail`.`product_quantity`) AS `quantity`
						FROM `sale_transaction` RIGHT JOIN `sale_transaction_detail`
							ON `sale_transaction`.`id` = `sale_transaction_detail`.`transaction_id`
						WHERE `object_id` = $object_id && `status` = 1
						GROUP BY `sale_transaction_detail`.`transaction_id`");
	$row = mysql_fetch_assoc($res);
	return round($row['quantity'], 3);
}

function GetProdQuantity($trans_id, $prod_id)
{
	$res = mysql_query("SELECT	`product_quantity`
						FROM	`sale_transaction_detail`
						WHERE	`transaction_id` = $trans_id && `production_id` = $prod_id");
	$row = mysql_fetch_assoc($res);
	return $row['product_quantity'];
}

function GetSumPrice($object_id)
{
    $res = mysql_query("SELECT ROUND(SUM(`sale_transaction_detail`.`cost` * `sale_transaction_detail`.`product_quantity`), 2 ) AS `cost`
						FROM `sale_transaction` RIGHT JOIN `sale_transaction_detail`
							ON `sale_transaction`.`id` = `sale_transaction_detail`.`transaction_id`
						WHERE `object_id` = $object_id && `status` = 1
						GROUP BY `sale_transaction_detail`.`transaction_id`");
	$row = mysql_fetch_assoc($res);
	return round($row['cost'], 2 );
}

function GetSumSelfPrice($object_id)
{
    $res = mysql_query("SELECT ROUND(SUM(`sale_transaction_detail`.`self_cost` * `sale_transaction_detail`.`product_quantity`), 2 ) AS `self_cost`
						FROM `sale_transaction` RIGHT JOIN `sale_transaction_detail`
							ON `sale_transaction`.`id` = `sale_transaction_detail`.`transaction_id`
						WHERE `object_id` = $object_id && `status` = 1
						GROUP BY `sale_transaction_detail`.`transaction_id`");
	$row = mysql_fetch_assoc($res);
	return round($row['self_cost'], 2 );
}

function SelectPOS()
{
	$arr = GetWarehouseMoney();

	$data = '		
		<div id="dialog-form">
		    <fieldset>
		    	<table class="dialog-form-table">
					<tr>
						<td style="width: 170px;"><label for="obj_id">აირჩიეთ სალარო</label></td>
						<td>
							<select id="obj_id" class="idls">' . GetObjectList() . '</select>
						</td>
					</tr>
				</table>
	        </fieldset>
			<fieldset>
		    	<table class="dialog-form-table">
					<tr>
						<td><label for="pos-money">თანხა  <span style="font-weight:bold;">დარბაზის</span> სალაროში :</label></td>
						<td><div  id="pos-money" style="display:inline;"></div><span style="font-weight:bold; color:red; font-size:17px; line-height:10px;">'. $arr .'</span> ლ</td>
					</tr>								
					<tr>
						<td><input type="button" value="არ ვეთანხმები" id="dont-confirm-pos" style="margin-left:30px; padding:5px 5px;"/> </td>
					</tr>				
				</table>
				<fieldset id="check-failed" style="visibility:hidden;">
					<legend>შენიშვნა</legend>				
					  <table>
						<tr>
						   <td><label for="pos_money_amount">თანხა სალაროში :</label></td>
						   <td><input type="text" id="pos_money_amount" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						<tr>   
						<tr>
						   <td><label for="reason">შენიშვნა :</label></td>
						   <td><textarea id="reason" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						<tr>   
					   </table>
				</fieldset>
	        </fieldset>
	    </div>';
	return $data;
}

function GetObjectList()
{
	$data = '';
    $req = mysql_query("SELECT `id`, `name`
						FROM `object`
						WHERE `type` = 9 AND `actived`=1");
		
	while( $res = mysql_fetch_assoc($req)){			
		$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
	}
		
	return $data;
}

function GetSuspendedPage($object_id)
{
	$data = '
		<div id="dialog-form">
		    <fieldset>
		    	<table class="dialog-form-inner-table">
					<tr>
						<th class="ui-state-default">ტრანზაქცია</th>
						<th class="ui-state-default">თარიღი</th>
						<td class="ui-state-default" style="width: 115px">&nbsp;</td>
						<td class="ui-state-default" style="width: 135px">&nbsp;</td>
					</tr>';
	$req = mysql_query("SELECT `id`, `start_date`
			FROM `sale_transaction`
			WHERE `object_id` = $object_id && `status` = 2");
		
	while( $res = mysql_fetch_assoc($req)){
		$data .= '
					<tr>
						<td>' . $res['id'] . '</td>
						<td>' . $res['start_date'] . '</td>
						<td><button class="restore_suspend_button" trans="' . $res['id'] . '">აღდგენა</button></td>
						<td><button class="cancel_suspend_button" trans="' . $res['id'] . '">წაშლა</button></td>
					</tr>';
	}
	$data .= '
				</table>
	        </fieldset>
	    </div>
        ';
	return $data;
}


//Function of produce **************************************************

function GetProdPage($object_id, $prod_id){
	
	$res = mysql_fetch_assoc(mysql_query("	SELECT production.name AS name
											FROM   production
											WHERE  production.id = $prod_id"));
	
	$data = '
		<div id="dialog-form">
		    <fieldset>
			<legend>ძირითადი ინფორმაცია</legend>
		    	<table class="dialog-form-inner-table">
					<tr style="background-color:#FFF">
						<td id="prod_id" style="display:none;">' . getProductID($res[name]) .'</td>
						<td style="width: 170px; height:60px !important;"><label for="prod_name" style="font-weight:bold;">პროდუქტი</label></td>
						<td style="padding-left:45px;"><input type="text" id="prod_name" style="font-size:15px !important; font-weight:bold; color:#a7313a; text-align:center; width:160px !important;" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res[name] . '" disabled/></td>
					</tr>
					<tr>
						<td style="width: 170px;"><label for="code" style="font-weight:bold;">რაოდენობა</label></td>
						<td style="padding-left:45px;">
							<form>
								<input type="button" value="-" class="btn btn-2 btn-2h1" style="margin-left:0px !important;" id="decrement"  onclick="if(this.form.number.value!=1) {this.form.number.value--;}">   <!-- -->
								<input type="text" class="textbox" id="prod_quantity" style="margin-left:0px !important;" name="number" value="1" min="1" disabled />
								<input type="button" value="+" class="btn btn-2 btn-2h2" style="margin-left:0px !important;" id="increment" onclick=" this.form.number.value++; ">  <!--  -->
							</form>
						</td>
					</tr>
				  </table>
			   </fieldset>
	    </div>';
		
	return $data;
}



function GetProdIngPage($object_id, $prod_id)
{
	$res = mysql_fetch_assoc(mysql_query("
											SELECT production.name
											FROM   production
											WHERE  production.id = $prod_id"));
	
	$res1 = mysql_query("SELECT 	production.id AS `id`,
									production.name AS `name`,
									recipie.default_amount AS `amount`,
									recipie.quantity AS `quantity`
									
						FROM 		recipie 
						LEFT JOIN 	production ON production.id = recipie.ingredient_id
						WHERE 		recipie.recipie_id = $prod_id AND recipie.visible = 1");
			
	$data = '
		<div id="dialog-form">
		    <fieldset>
			<legend>ძირითადი ინფორმაცია</legend>
		    	<table class="dialog-form-inner-table">
					<tr style="background-color:#FFF">
						<td id="prod_id" style="display:none;">' . getProductID($res['name']) .'</td>
						<td style="width: 170px; height:60px !important;"><label for="prod_name" style="font-weight:bold;">პროდუქტი</label></td>
						<td style="padding-left:45px;">
							<input type="text" id="prod_name" style="font-size:15px !important; font-weight:bold; color:#a7313a; text-align:center; width:160px !important;" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['name'] . '" disabled/>
						</td>
					</tr>
					<tr>				
						<td style="width: 170px;"><label for="code" style="font-weight:bold;">რაოდენობა</label></td>
						<td style="padding-left:45px;">
							<form>	
								<input type="button" value="-" class="btn btn-2 btn-2h1" style="margin-left:0px !important;" id="decrement"  onclick="if(this.form.number.value!=1) {this.form.number.value--;}">   <!-- -->
								<input type="text" class="textbox" id="prod_quantity" style="margin-left:0px !important;" name="number" value="1" min="0" disabled />
								<input type="button" value="+" class="btn btn-2 btn-2h2" style="margin-left:0px !important;" id="increment" onclick=" this.form.number.value++; ">  <!--  -->
							</form>										
						</td>			
<!--					<td>
							<input type="text" id="quantity" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'"/>
						</td>	
-->											
					</tr>
				</table>
	        </fieldset>
									
			<fieldset>
			<legend>ინგრედიენტები</legend>
					<table class="tableCheckClass" id="part_list"  style="width: auto;"  cellspacing=0 style=" vertical-align: baseline;"> <!-- cellspacing=0 is important, must stay -->
						<thead>
							<tr class="trCheckClass">
								<th class="thCheckClass" style="display:none;"></th>
								<th class="thCheckClass" style="width: 200px;">ტიპი</th>
								<th class="thCheckClass">#</th>
								<th class="thCheckClass">#</th>
							</tr>
						</thead>
					<tbody id="part_list_tbody">';	
										
		while ($row = mysql_fetch_assoc($res1)) {
			$data .= '<tr class="trCheckClass1">	
							<td style="display: none;" id="type_'.$row['id'].'"><span class="id_value">'.$row['id'].'</span></td>
							<td class="tdCheckClass" style="padding-top:22px !important; font-size:15px !important; font-weight:bold;">'.$row['name'].'</td>
							<td class="tdCheckClass">
								<form>	
									<input type="button" value="-" class="btn btn-2 btn-2h1" id="decrement_'.$row['id'].'" onclick="if(this.form.number.value!=0) {this.form.number.value--;}">   <!-- -->
									<input type="text" class="textbox" id="ingr_quantity_'.$row['id'].'" name="number" value="'.$row['amount'].'" min="0" disabled />
									<input type="button" value="+" class="btn btn-2 btn-2h2" id="increment_'.$row['id'].'" onclick=" this.form.number.value++; ">  <!--  -->
								</form>			
							</td>
							
							<td class="tdCheckClass">
									<input type="text" class="textbox" name="number2" id="quantity_'.$row['id'].'" value="'.round($row['quantity'],3).'" min="0"  disabled />
									<input type="text"  style="display:none;" id="id_quantity_'.$row['id'].'" value="'.$row['quantity'].'" />		
							</td>
					</tr>';		
		}
		
		$data .= '													
						</tbody>
					</table>
	        </fieldset>
	    </div>
        ';
	
	return $data;
}

function CheckProdExist($prod_id, $quantity, $object_id)
{
	$warehouse = GetWarehouseObject($object_id);
	
	$row = mysql_fetch_assoc(mysql_query("	SELECT 		SUM(`reserve`.`quantity` - `reserve`.`sold`) AS `quantity`
										  	FROM 		`reserve` 
											LEFT JOIN 	`object`
											ON 			`object`.`id` = `reserve`.`object_id`
										  	WHERE 		`object`.`id` = $warehouse && `reserve`.`production_id` = $prod_id
										  	GROUP BY 	`object`.`warehouse`	
										"));
	if($row['quantity'] >= $quantity){
		return true;
	}
	return false;
}

function GetTransactionId($object_id){
		$res = mysql_fetch_assoc(mysql_query("SELECT `id`
							FROM `sale_transaction`
							WHERE status = 1 && object_id = $object_id"));
		
		return $res['id'];
}

function PayDone($user_id, $object_id, $sum_cost, $sum_self_cost, $payed_money, $pay_type)
{
	$end_date = date('Y-m-d H:i:s');
	$trans_id = mysql_fetch_assoc(mysql_query("SELECT `sale_transaction`.`id` AS `id`
												FROM  `sale_transaction`
												WHERE `object_id` = $object_id && `status` = 1"));
	mysql_query("UPDATE
						`sale_transaction`
				  SET
				  		`user_id`           =  $user_id,
						`end_date`			=  '$end_date',
						`sum_self_cost`		=  $sum_self_cost,
						`sum_cost`          =  $sum_cost,
						`payed_money`       =  $payed_money,
						`pay_type`          =  $pay_type,
						`status`			=  0
				  WHERE `object_id` = $object_id && `status` = 1");
	


}

function Calculate($object_id){
	$result = mysql_query("	SELECT 			`production`.`id` AS id,
											`production`.`name` AS name,
											`sale_transaction_detail`.`product_quantity` AS quantity,
											`object`.`warehouse`AS  object
							FROM			`sale_transaction_detail` 
							INNER JOIN		`production`
								ON			`sale_transaction_detail`.`production_id` = `production`.`id`
							INNER JOIN		`sale_transaction`
								ON			`sale_transaction_detail`.`transaction_id` = `sale_transaction`.`id`
							LEFT JOIN		`object` ON `sale_transaction`.`object_id` = `object`.`id`
							WHERE			`sale_transaction`.`object_id` = $object_id  AND `sale_transaction`.`status` = 1");		
	

	
	
	
	$transaction_id = GetTransactionId($object_id);
	
	
	$myres = mysql_query("SELECT  sale_transaction_detail.id AS id, production_id AS prod_id  
							FROM  `sale_transaction_detail`
							WHERE sale_transaction_detail.transaction_id = $transaction_id");
	
	while ($row2 = mysql_fetch_assoc($myres)) {

		$req = mysql_fetch_assoc( $result );
		$res1 = mysql_query("SELECT	  	  recipie_producing.production_id AS id,
								          recipie_producing.quantity AS quantity
								FROM  	  recipie_producing
								LEFT JOIN sale_transaction_detail ON sale_transaction_detail.id = recipie_producing.transaction_detail_id
								WHERE 	  recipie_producing.recipie_id = $row2[prod_id] && sale_transaction_detail.id = $row2[id]");
			
		if(mysql_num_rows($res1) == 0){
			$row3 = mysql_fetch_assoc(mysql_query("SELECT `production_id` AS `id`, `product_quantity` AS `quantity`
													FROM  `sale_transaction_detail`
													WHERE `id` = $row2[id]"));
			SaleDone($row3['id'], $row3['quantity'], $req['object']); 
		}else{
				while($row1 = mysql_fetch_assoc($res1)){				
					SaleDone($row1['id'], $row1['quantity'], $req['object']); 
				}
		}
	}
	return false;
}

function GetWarehouseObject($object_id){
	$query  = mysql_query("	SELECT 	`warehouse`
							FROM  	`object`
							WHERE  	`id` = $object_id");
	$result = mysql_fetch_assoc($query);
	return $result['warehouse'];
}

function SaleDone($prod_id, $quantity, $object)
{
	$req_quantity = $quantity;
	$res = mysql_query("SELECT  	`reserve`.`id`,
									`reserve`.`production_id`,
									`reserve`.`object_id`,
									`reserve`.`sold`,
									`reserve`.`quantity` - `reserve`.`sold` AS `diff`,
									`reserve`.`create_date`
						FROM 		`reserve`
						WHERE 		`reserve`.`object_id` = $object && `reserve`.`production_id` = $prod_id
						ORDER BY 	`reserve`.`create_date` ASC" );
	
	while ($row = mysql_fetch_array($res)) {
		if ($req_quantity != 0) {
			if($row['diff'] > $req_quantity){
				$sum = $row['sold'] + $req_quantity;
				mysql_query("	UPDATE	`reserve`
								SET		`sold` = $sum
								WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else if($row['diff'] == $req_quantity){
				$sum = $row['sold'] + $row['diff'];
				mysql_query("	UPDATE	`reserve`
								SET		`sold` = $sum
								WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			}else{
				$sum = $row['sold'] + $row['diff'];
				mysql_query("	UPDATE	`reserve`
								SET		`sold` = $sum
								WHERE	`id` = $row[id]" );
				$req_quantity = $req_quantity - $row['diff'];
			}
		}
	}
}

function getMainMenu(){
	$res = mysql_query("	SELECT  `production_category`.`id`,
									`production_category`.`name`,
									`production_category`.`image`
							FROM 	`production_category`
							WHERE  	`production_category`.`actived`= 1 AND `production_category`.`pos_menu_visible` = 1
			");
	
	$data = '<tr class="trClassHall">';	
	for ($i = 1; $i <=4; $i++) {
		$row = mysql_fetch_assoc($res);
		if ($row['id'] && $row['image']) {
			$data.= '
					<td class="tdClassHall"><img  class="main" id="' . $row['id'] . '" src="media/uploads/images/category/' . $row['image'] . '" style="width: 135px; height: 135px;"/><div class="production_category_hall" id="' . $row['id'] . '">' . $row['name'] . '</div></td>
			  	';
		}else {
			$data.= '
						<td style="width: 135px; height: 135px;" class="tdClassHall">&nbsp;</td>
				  	';
		}
		
	}	
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 5; $i <=8; $i++) {
		$row = mysql_fetch_assoc($res);
		if ($row['id'] && $row['image']) {
				$data.= '
						<td class="tdClassHall"><img class="main" id="' . $row['id'] . '" src="media/uploads/images/category/' . $row['image'] . '" style="width: 135px; height: 135px; position:relative;"/><div class="production_category_hall" id="' . $row['id'] . '">' . $row['name'] . '</div></td>
				  	';
		}else {
			$data.= '
						<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>
				  	';
		}
	}
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 9; $i <=12; $i++) {
		$row = mysql_fetch_assoc($res);
		if ($row['id'] && $row['image']) {
				$data.= '
						<td class="tdClassHall"><img class="main" id="' . $row['id'] . '" src="media/uploads/images/category/' . $row['image'] . '" style="width: 135px; height: 135px;"/><div class="production_category_hall" id="' . $row['id'] . '">' . $row['name'] . '</div></td>
				  	';
		}else {
			$data.= '
						<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>
				  	';
		}
	}
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 13; $i <=16; $i++) {
		$row = mysql_fetch_assoc($res);
		if ($row['id'] && $row['image']) {
				$data.= '
						<td class="tdClassHall"><img class="main" id="' . $row['id'] . '" src="media/uploads/images/category/' . $row['image'] . '" style="width: 135px; height: 135px;"/><div class="production_category_hall" id="' . $row['id'] . '">' . $row['name'] . '</div></td>
				  	';
		}else {
			$data.= '
						<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>
				  	';
		}
	}
	
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 17; $i <=20; $i++) {
		$row = mysql_fetch_assoc($res);
		if ($row['id'] && $row['image']) {
			$data.= '
						<td class="tdClassHall"><img class="main" id="' . $row['id'] . '" src="media/uploads/images/category/' . $row['image'] . '" style="width: 135px; height: 135px;"/><div class="production_category_hall" id="' . $row['id'] . '">' . $row['name'] . '</div></td>
				  	';
		}else {
			$data.= '
						<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>
				  	';
		}
	}
	
	$data .= '</tr>';
	
	return $data;
}

function GetPrice($production_id){
	
	$res = mysql_query("SELECT ROUND(`price`,2) AS `price`
			FROM `reserve`
			WHERE `production_id` = $production_id
			GROUP BY `production_id`");

	$row = mysql_fetch_assoc($res);
	return $row['price'];
	
}

function getSubMenu($category_id){
	$res = mysql_query("	SELECT    production.id,
								      production.image,
									  production.name  AS `name`,
      					              ROUND(`pricelist`.`price_wholesale`,2) AS `sp_price`
					       FROM       production
						   LEFT JOIN  pricelist ON pricelist.production_id = production.id
					       LEFT JOIN  production_category ON production_category.id = production.pos_menu_category
					       LEFT JOIN  reserve ON production.id = reserve.production_id
					       WHERE      production_category.id = $category_id AND production.id IN (SELECT pricelist.production_id FROM pricelist)
					       GROUP BY   production.id
					       HAVING     SUM(reserve.quantity - reserve.sold)>0
			
							UNION
			
						   SELECT      production.id AS `id`,
									   production.image AS `image`,
			            			   production.name  AS `name`,
									   ROUND(`pricelist`.`price_wholesale`,2) AS `sp_price`
					       FROM        production
						   LEFT JOIN   pricelist ON production.id = pricelist.production_id
					       LEFT JOIN   production_category ON production_category.id = production.pos_menu_category
						   LEFT JOIN   recipie ON recipie.recipie_id = production.id
						   LEFT JOIN   reserve ON recipie.ingredient_id = reserve.production_id
					       WHERE       production_category.id = $category_id AND production.id IN (SELECT pricelist.production_id FROM pricelist)
					       GROUP BY    production.id
					       HAVING      SUM(reserve.quantity - reserve.sold)>0");

	$data = '<tr class="trClassHall">';
	
	$data.= '
				<td class="tdClassHall"><img class="backTop" id="backTop" src="media/images/pos/back.png" style="width: 135px; height: 135px;"/></td>
			';
	
	
	for ($i = 1; $i <=3; $i++) {
		$row = mysql_fetch_assoc($res);
		
		if(($row['id'] && $row['image'])){
						$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		   }else{
					$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';			
		}

	 }

	$data .= '</tr>';

	$data .= '<tr class="trClassHall">';
	for ($i = 4; $i <=7; $i++) {
		$row = mysql_fetch_assoc($res);
		
		if(($row['id'] && $row['image'])){
						$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		   }else{
					$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';			
		}
	}
	$data .= '</tr>';

	$data .= '<tr class="trClassHall">';
	for ($i = 8; $i <=11; $i++) {
			$row = mysql_fetch_assoc($res);
		
		if(($row['id'] && $row['image'])){
						$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		   }else{
					$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';			
		}
	}
	$data .= '</tr>';

	$data .= '<tr class="trClassHall">';
	for ($i = 12; $i <=15; $i++) {
		$row = mysql_fetch_assoc($res);
		
		if(($row['id'] && $row['image'])){
					$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		}else{
			$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';
		}
	}
	
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 16; $i <=19; $i++) {
		$row = mysql_fetch_assoc($res);
	
		if(($row['id'] && $row['image'])){
			$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		}else{
			$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';
		}
	}
	
	$data .= '</tr>';
	
	$data .= '<tr class="trClassHall">';
	for ($i = 20; $i <=23; $i++) {
		$row = mysql_fetch_assoc($res);
	
		if(($row['id'] && $row['image'])){
			$data.= '<td class="tdClassHall"><img class="productions" id="' . $row['id'] . '" src="media/uploads/images/production/' . $row['image'] . '" style="width: 135px; height: 135px;" /><div class="production_name_hall" id="' . $row['id'] . '">' . $row['name'] . '</div><div class="production_price_hall" id="' . $row['id'] . '">'.$price = $row['sp_price'].' <span>ლ</span></div></td>';
		}else{
			$data.= '<td class="tdClassHall" style="width: 135px; height: 135px;">&nbsp;</td>';
		}
	}

	$data .= '</tr>';

	return $data;
}

function GetAddSalary($object_id){
	$pos_money = GetWarehouseMoney();
	$data = "";

	$data.='<div id="dialog-form">
			    <fieldset>
			    	<table class="dialog-form-table">
						<tr>
							<td>ამჟამად დარბაზის სალაროში არის</td>
							<td style="font-weight:bold;"><span style="color:red; font-size:20px; line-height:12px;">'. $pos_money .'</span> ლარი</td>
						</tr>
					</table>
		        </fieldset>
				<fieldset>
					<legend>მომხმარებლის მონაცემები</legend>
			    	<table class="dialog-form-table">
						<tr>
							<td style="width: 170px;"><label for="username">მომხმარებლის სახელი:</label></td>
							<td><input type="text" id="username"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
						<tr>
							<td style="width: 170px;"><label for="password">პაროლი:</label></td>
							<td><input type="password" id="password"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
					</table>
				</fieldset>
				<fieldset>
					<legend>თანხის დამატება</legend>
			    	<table class="dialog-form-table">
						<tr>
							<td style="width: 170px;"><label for="money-amount">თანხის რაოდენობა:</label></td>
							<td><input type="text" id="money-amount"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
						<tr>
							<td style="width: 170px;"><label for="notice">შენიშვნა:</label></td>
							<td><textarea rows="3" id="notice" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
					</table>
		        </fieldset>
			</div>';

	return $data;
}

function GetTakeSalary($object_id){
	$pos_money = GetWarehouseMoney();
	$data = "";

	$data.='<div id="dialog-form">
			    <fieldset>
			    	<table class="dialog-form-table">
						<tr>
							<td>ამჟამად დარბაზის სალაროში არის</td>
							<td style="font-weight:bold;"><span style="color:red; font-size:20px; line-height:12px;">'. $pos_money .'</span> ლარი</td>
						</tr>
					</table>
		        </fieldset>
				<fieldset>
					<legend>მომხმარებლის მონაცემები</legend>
			    	<table class="dialog-form-table">
						<tr>
							<td style="width: 170px;"><label for="username">მომხმარებლის სახელი:</label></td>
							<td><input type="text" id="username"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
						<tr>
							<td style="width: 170px;"><label for="password">პაროლი:</label></td>
							<td><input type="password" id="password"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
					</table>
				</fieldset>
				<fieldset>
					<legend>თანხის გატანა</legend>
			    	<table class="dialog-form-table">
						<tr>
							<td style="width: 170px;"><label for="take-money-amount">თანხის რაოდენობა:</label></td>
							<td><input type="text" id="take-money-amount"class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
						<tr>
							<td style="width: 170px;"><label for="take-notice">შენიშვნა:</label></td>
							<td><textarea rows="3" id="take-notice" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" /></td>
						</tr>
					</table>
		        </fieldset>
			</div>';

	return $data;
}

function printCheck($price){
	$fprice  = round($price,2);
	$content = "S,1,______,_,__;;$fprice;;1;1;2;0;0;
T,1,______,_,__;";
	$file = '../../media/print/DEFEXEC.txt';

	file_put_contents($file, $content);

	
}

?>